import React, { useEffect, useCallback, useReducer, Dispatch, memo, forwardRef } from 'react';
import { Title } from '@/components/common'
import { EditStatus } from 'gantd';
import LoupeSelect from '@/components/form/loupeselect';
import { searchFormschema, searchUISchema, columns } from './schema'
import { ActionType, StateType, initState, reducer } from '../codelistselector/reducer'
import { fetchEntryListApi } from './service';
/**
 * 对象选择器
 */

export interface ObjectSelectorProps {
	value?: string | string[],
	onChange?: (value: string | string[]) => void,
	bizEntryId?: string,
	entryType?: string,
	bizType: string,
	defalutValue?: string | string[],
	disabled?: boolean,
	edit?: EditStatus.EDIT | EditStatus.CANCEL | EditStatus.SAVE,
	allowEdit?: boolean,
	valueProp?: string
}
function ObjectSelector(props: ObjectSelectorProps, ref: any) {
	const {
		defalutValue,
		allowEdit,
		valueProp = "dbName",
		value: _value,
		onChange,
		bizEntryId,
		entryType,
		bizType,
		edit = EditStatus.EDIT,
		...otherProps }
		= props;

	const [state, dispatch]: [StateType, Dispatch<ActionType>] = useReducer(reducer, initState);

	const { value, dropDownData, modalData, loading, total, params } = state;

	const queryBySelect = useCallback(async () => {
		const { content } = await fetchEntryListApi({ ...initState.params, bizEntryId, entryType, bizType });
		dispatch({ type: "saveDropDownData", payload: content });
	}, [bizEntryId, entryType, bizType])

	useEffect(() => {
		dispatch({ type: "saveValue", payload: _value });
	}, [_value, dispatch])

	useEffect(() => {
		defalutValue && dispatch({ type: "saveValue", payload: defalutValue });
		if (bizType) queryBySelect()
	}, [bizEntryId, entryType, bizType])

	const onValueChange = useCallback((value) => {
		dispatch({ type: "saveValue", payload: value });
		if (onChange) onChange(value)
	}, [onChange])

	const queryByModal = useCallback(async (params) => {
		await dispatch({ type: "save", payload: { params, loading: true } });
		const { totalCount, content } = await fetchEntryListApi({ ...params, bizEntryId, entryType, bizType });
		dispatch({ type: 'save', payload: { total: totalCount, modalData: content, loading: false } })
	}, [bizEntryId, entryType, bizType])

	const onChangePage = useCallback((beginIndex, pageSize) => {
		// const beginIndex = (current - 1) * pageSize;
		queryByModal({ ...params, pageSize, beginIndex })
	}, [params])

	const onModalVisibleChange = useCallback(async (visible) => {
		visible ? queryByModal(initState.params) : dispatch({ type: "initModal" })
	}, [])
	
	const onSearch = useCallback((searchParams) => {
		queryByModal({ ...searchParams });
	}, [params])

	return <LoupeSelect
		{...otherProps}
		selectorId={`LoupeSelect-${bizEntryId}-${entryType}-${bizType}`}
		value={value}
		dataSource={dropDownData}
		useCache={false}
		edit={edit}
		labelProp='title'
		valueProp={valueProp}
		onChange={onValueChange}
		multiple={false}
		allowEdit={allowEdit}
		viewProps={{
			title: <Title title={tr("业务对象")} />,
			searchFormTitle: <Title title={tr("条件查询")} />,
			onModalVisibleChange,
			viewKey: `Loupess-${bizEntryId}-${entryType}-${bizType}`,
			uiSchema: searchUISchema,
			schema: searchFormschema,
			columns,
			dataSource: modalData,
			loading: loading,
			onSearch,
			//分页自定义
			pagination: {
				total: total, //总条数
				beginIndex: params.beginIndex, //当前页数
				pageSize: params.pageSize, //每页显示数
				onChange: onChangePage
			}
		}}
	/>
}

export default memo(forwardRef(ObjectSelector))